174. Dungeon Game - LeetCode Solution


Binary Search Dynamic Programming

Python Code:

class Solution:
    def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:
        m, n = len(dungeon), len(dungeon[0])

        memo = [[[None] * 2 for _ in range(n)] for _ in range(m)] 
        
        def check(h, i, j):
            if memo[i][j][0] and h >= memo[i][j][0]:
                return True
            if memo[i][j][1] and h <= memo[i][j][1]:
                return False
            if h <= 0:
                return False
              
                
            result = None
            
            
            
            if i == m-1 and j == n-1:
                result =  h + dungeon[i][j] > 0
            elif i == m-1:
                result = check(h + dungeon[i][j], i, j+1)
            elif j == n-1:
                result = check(h + dungeon[i][j], i+1, j)
            else:
                result = check(h + dungeon[i][j], i+1, j) or check(h + dungeon[i][j], i, j+1)
            
            if result: 
                memo[i][j][0] = h
                return True
            else:
                memo[i][j][1] = h
                return False

            
        low, high = 0, 2**31
        while low < high:
            mid = low + (high-low)//2
            if check(mid, 0, 0):
                high = mid
            else:
                low = mid + 1

        return low
        


Comments

Submit
0 Comments
More Questions

46A - Ball Game
114A - Cifera
776A - A Serial Killer
25B - Phone numbers
1633C - Kill the Monster
1611A - Make Even
1030B - Vasya and Cornfield
1631A - Min Max Swap
1296B - Food Buying
133A - HQ9+
1650D - Twist the Permutation
1209A - Paint the Numbers
1234A - Equalize Prices Again
1613A - Long Comparison
1624B - Make AP
660B - Seating On Bus
405A - Gravity Flip
499B - Lecture
709A - Juicer
1358C - Celex Update
1466B - Last minute enhancements
450B - Jzzhu and Sequences
1582C - Grandma Capa Knits a Scarf
492A - Vanya and Cubes
217A - Ice Skating
270A - Fancy Fence
181A - Series of Crimes
1638A - Reverse
1654C - Alice and the Cake
369A - Valera and Plates